﻿using System;
using System.Collections.Generic;
using Dapper;
using System.Text;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace VOL.Core.DBManager
{
    public static class MySql_Helper
    {
        public static JObject get_appsettings()
        {
            JObject jObject = new JObject();
            string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;//获取应用程序运行的目录
            System.IO.StreamReader file = System.IO.File.OpenText(path + "/appsettings.json");
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                jObject = JObject.Load(reader);
            }
            return jObject;
        }
        public static List<T> query<T>(string sqlstr, string ConnStr)
        {

            JObject jj = get_appsettings();
            string conntionstring = jj.SelectToken("Connection").SelectToken("mysql_db").SelectToken(ConnStr).ToString();//读取json文件节点数据,数据库连接配置信息

            List<T> rtnlist = null;
            using (MySqlConnection conn = new MySqlConnection(conntionstring))
            {
                
                conn.Open();
                rtnlist = (List<T>)conn.Query<T>(sqlstr);
                conn.Close();
            }
            return rtnlist;
        }
        public static dynamic query_common(string sqlstr, string ConnStr)
        {
            JObject jj = get_appsettings();
            string conntionstring = jj.SelectToken("Connection").SelectToken("mysql_db").SelectToken(ConnStr).ToString();//读取json文件节点数据,数据库连接配置信息

            dynamic rtnlist = null;
            using (MySqlConnection conn = new MySqlConnection(conntionstring))
            {
                conn.Open();
                rtnlist = conn.Query(sqlstr).AsList();
                conn.Close();
            }
            return rtnlist;
        }

        public static int Execute(string sqlstr, string ConnStr)
        {
            JObject jj = get_appsettings();
            string conntionstring = jj.SelectToken("Connection").SelectToken("mysql_db").SelectToken(ConnStr).ToString();//读取json文件节点数据,数据库连接配置信息

            int rnt_num = 0;
            using (MySqlConnection conn = new MySqlConnection(conntionstring))
            {
                conn.Open();
                rnt_num = conn.Execute(sqlstr);
                conn.Close();
            }
            return rnt_num;
        }
    }
}
